# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.qr import make_code

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'me00051': {
        # 猕猴桃支付 alipay h5 2.5% 10-5000 witch
        'API_KEY': 'b4f618d4-6c90-4e00-8f5f-dff2a666e952',
        'gateway': 'https://me00051.wf51job.com/pay/gateway.api',
        'query_gateway': 'https://me00051.wf51job.com/pay/orderInfo.api',
    },
    'me00069': {
        # 猕猴桃支付 支付宝扫码 3.2% 200以下 loki
        'API_KEY': '077b096c-a94a-45ce-bef6-c6167f5afda5',
        'gateway': 'https://me00051.wf51job.com/pay/gateway.api',
        'query_gateway': 'https://me00051.wf51job.com/pay/orderInfo.api',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(d, key):
    s = 'merNum={}&orderNum={}&notifyUrl={}&payType={}&amount={}&secreyKey={}'.format(d['merNum'], d['orderNum'],
                                                                                      d['notifyUrl'], d['payType'],
                                                                                      d['amount'], key)
    _LOGGER.info("nihoutaopay sign str: %s", s)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = 'orderNum={}&payTime={}&payStatus={}&secreyKey={}'.format(d['orderNum'], d['payTime'],
                                                                  d['payStatus'], key)
    _LOGGER.info("nihoutaopay notify sign str: %s", s)
    return _gen_sign(s)


def generate_query_sign(d, key):
    s = 'merNum={}&orderNum={}&secreyKey={}'.format(d['merNum'], d['orderNum'], key)
    _LOGGER.info("nihoutaopay notify sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("nihoutaopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    '''
    支付类型	对应支付
    2	支付宝扫码
    3	支付宝H5
    4	微信扫码
    5	云闪付
    6	银联快捷
    7	微信h5
    '''
    if service == 'alipay':
        return 3
    elif service == 'alipay_scan':
        return 2
    elif service == 'wechat_h5':
        return 7
    elif service == 'wechat_scan':
        return 4
    elif service == 'unionpay':
        return 6
    elif service == 'cloud_flash':
        return 6
    return 3


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merNum', app_id),
        ('payType', _get_pay_type(service)),
        ('amount', '%.2f' % pay_amount),
        ('orderNum', str(pay.id)),
        ('notifyUrl', '{}/pay/api/{}/nihoutaopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("nihoutaopay create: %s", json.dumps(dict(parameter_dict)))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=3)
    _LOGGER.info('nihoutaopay create rsp, %s, order_id is: %s', response.text, parameter_dict['orderNum'])
    data = json.loads(response.text)
    if service == 'alipay_scan':
        template_data = {'base64_img': make_code(data['qrCode']), 'amount': parameter_dict['amount']}
        t = get_template('qr_alipay_miaofu.html')
        html = t.render(Context(template_data))
        cache_id = redis_cache.save_html(pay.id, html)
        _LOGGER.info("miaofupay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    else:
        return {'charge_info': data['qrCode']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("nihoutaopay notify body: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['orderNum']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('nihoutaopay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['payStatus'])
    trade_no = data['orderNum']
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 0.待支付 1.支付成功 2.支付失败
    if trade_status == 1 and total_fee > 0.0:
        _LOGGER.info('nihoutaopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('orderNum', str(pay_id)),
        ('merNum', app_id),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('nihoutaopay query data, %s', json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict), headers=headers, timeout=3)
    _LOGGER.info('nihoutaopay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        _LOGGER.info("nihoutaopay query response body: %s", data)
        mch_id = pay_order.mch_id
        trade_status = data['data']['status']
        total_fee = float(data['data']['amount'])
        trade_no = data['data']['orderNum']
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 0.待支付 1.支付成功 2.支付失败
        if trade_status == 1:
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('nihoutaopay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
